<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>rabbitMQ | 静待花开</title><meta name="author" content="brad 随风起舞"><meta name="copyright" content="brad 随风起舞"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="java客户端连接到中间件每个使用AMQP的应用程序都需要与AMQP代理建立连接。默认情况下，RabbitMQ（以及任何其他1.0版之前的其他AMQP代理）通过TCP作为端口5672（即IANA分配的端口）上的可靠传输协议工作。  在java RabbitMQ客户端库导入所需类  import com.rabbitmq.client.Channel;   import com.rabbitmq.c">
<meta property="og:type" content="article">
<meta property="og:title" content="rabbitMQ">
<meta property="og:url" content="https://zhangbo4881820.gitee.io/myblog/posts/39854/index.html">
<meta property="og:site_name" content="静待花开">
<meta property="og:description" content="java客户端连接到中间件每个使用AMQP的应用程序都需要与AMQP代理建立连接。默认情况下，RabbitMQ（以及任何其他1.0版之前的其他AMQP代理）通过TCP作为端口5672（即IANA分配的端口）上的可靠传输协议工作。  在java RabbitMQ客户端库导入所需类  import com.rabbitmq.client.Channel;   import com.rabbitmq.c">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png">
<meta property="article:published_time" content="2019-12-09T02:57:47.000Z">
<meta property="article:modified_time" content="2023-09-07T09:44:01.904Z">
<meta property="article:author" content="brad 随风起舞">
<meta property="article:tag" content="消息中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png"><link rel="shortcut icon" href="/myblog/img/favicon.png"><link rel="canonical" href="https://zhangbo4881820.gitee.io/myblog/posts/39854/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/myblog/css/index.css"><link rel="stylesheet" href="/myblog/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="/myblog/css/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = {
  root: '/myblog/',
  algolia: undefined,
  localSearch: {"path":"/myblog/search.xml","preload":false,"top_n_per_article":1,"unescape":false,"languages":{"hits_empty":"找不到您查询的内容：${query}","hits_stats":"共找到 ${hits} 篇文章"}},
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'rabbitMQ',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2023-09-07 17:44:01'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 7.0.0-rc2"><link rel="alternate" href="/myblog/atom.xml" title="静待花开" type="application/atom+xml">
</head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><hr class="custom-hr"/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog-info"><a href="/myblog/" title="静待花开"><span class="site-name">静待花开</span></a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search" href="javascript:void(0);"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/myblog/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 分享</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/myblog/Gallery/"><i class="fa-fw fas fa-images"></i><span> 照片</span></a></li><li><a class="site-page child" href="/myblog/music/"><i class="fa-fw fas fa-music"></i><span> 音乐</span></a></li><li><a class="site-page child" href="/myblog/movies/"><i class="fa-fw fas fa-video"></i><span> 视频</span></a></li></ul></div><div class="menus_item"><a class="site-page" href="/myblog/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/myblog/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">rabbitMQ</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2019-12-09T02:57:47.000Z" title="发表于 2019-12-09 10:57:47">2019-12-09</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-09-07T09:44:01.904Z" title="更新于 2023-09-07 17:44:01">2023-09-07</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/myblog/categories/rabbitMQ/">rabbitMQ</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="rabbitMQ"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="java客户端连接到中间件"><a href="#java客户端连接到中间件" class="headerlink" title="java客户端连接到中间件"></a>java客户端连接到中间件</h1><p>每个使用AMQP的应用程序都需要与AMQP代理建立连接。默认情况下，RabbitMQ（以及任何其他1.0版之前的其他AMQP代理）通过TCP作为端口5672（即IANA分配的端口）上的可靠传输协议工作。</p>
<ol>
<li><p>在java RabbitMQ客户端库导入所需类</p>
<pre><code> import com.rabbitmq.client.Channel; 
 import com.rabbitmq.client.Connection; 
 import com.rabbitmq.client.ConnectionFactory;
</code></pre>
</li>
<li><p>创建ConnectionFactory客户端实例:</p>
<pre><code> ConnectionFactory factory = new ConnectionFactory();
</code></pre>
</li>
<li><p>设置连接选项:</p>
<pre><code> factory.setHost(rabbitMQhostname);
</code></pre>
</li>
<li><p>连接到RabbitMQ中间件</p>
<pre><code> Connection connection = factory.newConnection();
</code></pre>
</li>
<li><p>从已创建的连接中创建一个频道</p>
<pre><code> Channel channel = connection.createChannel();
</code></pre>
</li>
<li><p>一旦我们完成RabbitMQ的工作,需要对资源进行关闭.</p>
<pre><code> channel.close(); 
 connection.close();
</code></pre>
</li>
</ol>
<p><strong>最佳实践是打开连接并与其他线程共享。每个线程都会创建，使用和销毁其自己的独立通道。</strong></p>
<h1 id="参数讲解"><a href="#参数讲解" class="headerlink" title="参数讲解"></a>参数讲解</h1><ol>
<li><p><strong>Virtual hosts:</strong><br>这是个管理容器,它们允许在一个RabbitMQ实例中配置许多逻辑上独立的代理主机，以使许多不同的独立应用共享同一RabbitMQ服务器。<br>可以为每个虚拟主机配置其独立的权限，交换和队列集，并将在逻辑上分离的环境中工作。</p>
</li>
<li><p><strong>connection URI:</strong><br>通过String类型的字符指定一个连接选项:</p>
<pre><code> ConnectionFactory factory = new ConnectionFactory(); 
 String uri=&quot;amqp://user:pass@hostname:port/vhost&quot;; 
 factory.setUri(uri);
</code></pre>
</li>
</ol>
<p>这个连接必须遵守RFC3986中指定的格式(<a href="http://www.ietf.org/rfc/rfc3986.txt">http://www.ietf.org/rfc/rfc3986.txt</a>)</p>
<h1 id="生产消息"><a href="#生产消息" class="headerlink" title="生产消息"></a>生产消息</h1><pre><code>//创建队列
  String myqueue = &quot;myFirstQueue&quot;;
channel.queueDeclare(myqueue,true,false,false,null);
//然后创建消息
   String message = &quot;My message TO MyFirstqueue&quot;;
channel.basicPublish(&quot;&quot;,myqueue,null,message.getBytes());
 //再次发送,使用不同的选项
channel.basicPublish(&quot;&quot;,myqueue, MessageProperties.PERSISTENT_TEXT_PLAIN,message.getBytes());
</code></pre>
<p><strong>queueDeclare方法的参数意思:</strong></p>
<ul>
<li>queue: 队列的名字</li>
<li>durable: 指定队列的生存周期,如果要持久到服务器重启后仍然存在需要指定为true</li>
<li>exclusive: 这指定队列是否仅限于此连接.</li>
<li>autoDelete: 这指定队列一旦RabbitMQ中间件不在使用那么是否自动删除该队列</li>
<li>arguments: 这是队列构造参数的可选映射.</li>
</ul>
<p><strong>basicPublish方法</strong></p>
<pre><code>void basicPublish(java.lang.String exchange, java.lang.String routingKey, AMQP.BasicProperties props, byte[] body) throws java.io.IOException
</code></pre>
<p>在我们例子中<code>exchange</code>参数被设置为””,这就是默认的<code>exchange</code>,并且<code>routingKey</code>参数被设置为队列名字.这种情况下,消息会被直接发送到<code>routingKey</code>指定的队列上.<code>body</code>参数被设置成我们消息的二进制数组.<code>props</code>参数设置为null作为默认,这是消息的属性,稍后讨论.</p>
<p>再次发送的时候<code>props</code>参数设置为<code>MessageProperties.PERSISTENT_TEXT_PLAIN</code>.这种方式去访问RabbitMQ并标记这条消息作为持久消息.</p>
<p>如果队列被声明为持久的,消息被标记为持久的,那么会存入硬盘,如果两个条件丢失任何一个条件,消息就会存于内存中.如果存于内存中,那么rabbitMQ只要重启数据就没了,但是传递和获取消息的速度很快.</p>
<h1 id="检查rabbitmq状态"><a href="#检查rabbitmq状态" class="headerlink" title="检查rabbitmq状态"></a>检查rabbitmq状态</h1><p>命令行查看当前存在的队列:</p>
<pre><code>rabbitmqclt list_queues
</code></pre>
<p>检查队列是否已经存在:</p>
<pre><code>channel.queueDeclare()
channel.queueDeclarePassive().
</code></pre>
<p>为了确保特定队列已经存在，用channel.queueDeclarePassive（）替换channel.queueDeclare（）。如果队列已经存在，则这两种方法的行为是相同的。但是如果没有，第一个将默默创建它并返回（这实际上是最常用的情况），后者将引发异常</p>
<h1 id="消费消息"><a href="#消费消息" class="headerlink" title="消费消息"></a>消费消息</h1><ol>
<li><p>定义想要去消费的队列</p>
<pre><code> String myQueue=&quot;myFirstQueue&quot;; 
 channel.queueDeclare(myQueue, true, false, false, null);
</code></pre>
</li>
<li><p>定义一个指定的消费类继承<code>DefaultConsumer</code></p>
<pre><code> public class ActualConsumer extends DefaultConsumer &#123;

     public ActualConsumer(Channel channel) &#123;
         super(channel);
     &#125;

     @Override
     public void handleDelivery(String consumerTag,
                                Envelope envelope,
                                AMQP.BasicProperties properties, byte[] body) throws IOException &#123;
         String message = new String(body);
         System.out.println(&quot;received: &quot;+message);
     &#125;
 &#125;
</code></pre>
</li>
<li><p>创建一个消费对象,绑定我们的channel:</p>
<pre><code> ActualConsumer consumer = new ActualConsumer(channel);
</code></pre>
</li>
<li><p>开始消费信息</p>
<pre><code> String consumerTag = channel.basicConsume(myQueue, true, consumer);
</code></pre>
</li>
<li><p>完成后停止消费</p>
<pre><code> channel.basicCancel(consumerTag);
</code></pre>
</li>
</ol>
<p>激活了myQueue的使用者，Java客户端库开始从RabbitMQ代理上的该队列获取消息，并为每个队列调用handleDelivery（）</p>
<h2 id="消费线程和阻塞语义"><a href="#消费线程和阻塞语义" class="headerlink" title="消费线程和阻塞语义"></a>消费线程和阻塞语义</h2><p>绑定到一个channel的所有消费者将由线程池中的单个线程执行；但是，来自不同channel的使用者可能由同一线程处理。因此，重要的是要避免使用方方法中的持久操作，以避免阻塞其他使用方。</p>
<p>我们可以自己处理消费者线程池,这并不是强制的.</p>
<pre><code>ExecutorService eService = Executors.newFixedThreadPool(10); 
Connection connection = factory.newConnection(eService);
</code></pre>
<p>在管理它的同时，我们还负责终止它</p>
<pre><code>eService.shutdown();
</code></pre>
<p>如果你不创建ExecutorService线程池,java客户端会在连接被创建的时候创建一个线程池,一旦你关闭对应的连接那么该线程池就会关闭.</p>
<p><strong>阻塞语义</strong></p>
<p>也可以使用阻塞语义，但是如果这种方法不用于简单的应用程序和测试用例，我们强烈建议不要这样做。使用消息的配方是无阻塞的</p>
<h1 id="使用JSON序列化body"><a href="#使用JSON序列化body" class="headerlink" title="使用JSON序列化body"></a>使用JSON序列化body</h1><ol>
<li><p>首先导json包</p>
<pre><code> import com.rabbitmq.tools.json.JSONWriter;
</code></pre>
</li>
<li><p>创建一个非持久的队列:</p>
<pre><code> String myQueue=&quot;myJSONBodyQueue_4&quot;; 
 channel.queueDeclare(MyQueue, false, false, false, null);
</code></pre>
</li>
<li><p>创建一个book类的列表并用例子数据填入:</p>
<pre><code> List&lt;Book&gt;newBooks = new ArrayList&lt;Book&gt;(); 
     for (inti = 1; i&lt; 11; i++) &#123; 
         Book book = new Book(); 
         book.setBookID(i); 
         book.setBookDescription(&quot;History VOL: &quot; + i ); 
         book.setAuthor(&quot;John Doe&quot;); 
         newBooks.add(book); 
     &#125;
</code></pre>
</li>
<li><p>现在可以序列化<code>newBooks</code>使用JSONwriter实例:</p>
<pre><code> JSONWriter rabbitmqJson = new JSONWriter(); 
 String jsonmessage = rabbitmqJson.write(newBooks);
</code></pre>
</li>
<li><p>最终,我们可以发送json消息</p>
<pre><code> channel.basicPublish(&quot;&quot;,MyQueue,null, jsonmessage.getBytes());
</code></pre>
</li>
</ol>
<p>当然我们正常项目中都是用更强大的json工具.比如<a href="http://jackson.codehaus.org/">jackson</a>或者<a href="https://code.google.com/p/google-gson/">google-gson</a></p>
<h1 id="对消息使用RPC"><a href="#对消息使用RPC" class="headerlink" title="对消息使用RPC"></a>对消息使用RPC</h1><p>**Remote Procedure Calls(RPC)**是普遍用于客户端服务结构.需要客户端去对服务端执行一些动作,然后等待服务端的响应</p>
<p>消息传递范例试图采用即发即弃的消息传递样式实施完全不同的方法，但是可以使用设计正确的AMQP队列来执行和增强RPC，如下图所示：</p>
<p><img src="/myblog/image/RPCdiagram.png"></p>
<p>以图形方式描绘了请求队列与响应者相关联，答复队列与调用者相关联。但是，当我们使用RabbitMQ时，所有涉及的同级（调用方和响应方）都是AMQP客户端。</p>
<p>执行下面的步骤实现RPC响应方</p>
<ol>
<li><p>定义一个请求队列,响应者将会在其中等待RPC请求</p>
<pre><code> channel.queueDeclare(requestQueue, false, false, false, null);
</code></pre>
</li>
<li><p>定义指定的消费者RpcResponderConsumer并且复写DefaultConsumer.handleDelivery().对于每个RPC请求,消费者将会:</p>
<ul>
<li><p>在RPC请求中执行一个需求的动作</p>
</li>
<li><p>准备响应消息</p>
</li>
<li><p>在回应属性中设置相关ID通过以下代码:</p>
<pre><code>  BasicProperties replyProperties = new BasicProperties.Builder().correlationId(properties. getCorrelationId()).build();
</code></pre>
</li>
<li><p>在回应队列中发布回复</p>
<pre><code>  getChannel().basicPublish(&quot;&quot;, properties.getReplyTo(), replyProperties, reply.getBytes());
</code></pre>
</li>
<li><p>向RPC发送ack</p>
<pre><code>  getChannel().basicAck(envelope.getDeliveryTag(), false);
</code></pre>
</li>
</ul>
</li>
<li><p>开始消费消息，直到我们停止消费为止</p>
</li>
</ol>
<p>执行下面的步骤实现RPC调用方</p>
<ol>
<li><p>定义请求队列,响应者将会在其中等待RPC请求</p>
<pre><code> channel.queueDeclare(requestQueue, false, false, false, null);
</code></pre>
</li>
<li><p>创建一个临时,私有,自动删除的回复队列</p>
<pre><code> String replyQueue = channel.queueDeclare().getQueue();
</code></pre>
</li>
<li><p>定义指定的消费者RpcCallerConsumer,它将会收到并处理RPC回复.</p>
<ul>
<li><p>允许指定获取回复时的处理方式（在我们的示例中，通过定义AddAction()）</p>
</li>
<li><p>复写handleDelivery():</p>
<pre><code>  public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws java.io.IOException &#123; 
      String messageIdentifier = properties.getCorrelationId(); 
      String action = actions.get(messageIdentifier); 
      actions.remove(messageIdentifier); 
      String response = new String(body); 
      OnReply(action, response); 
  &#125;
</code></pre>
</li>
</ul>
</li>
<li><p>开始消费回复消息通过<code>channel.basicConsume()</code></p>
</li>
<li><p>准备序列化请求(messageRequest 例子中的)</p>
</li>
<li><p>初始化任意的唯一消息标识符（messageIdentifier）</p>
</li>
<li><p>通过将动作与messageIdentifier绑定，定义使用者获得相应答复时的处理方式。在我们的示例中，我们通过调用自定义方法consumer.AddAction（）来完成此操作。</p>
</li>
<li><p>将消息发布到requestqueue，设置其属性:</p>
<pre><code> BasicProperties props = new BasicProperties.Builder()
 .correlationId(messageIdentifier)
 .replyTo(replyQueue).build(); 
 channel.basicPublish(&quot;&quot;, requestQueue, props,messageRequest.getBytes());
</code></pre>
</li>
</ol>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog">brad 随风起舞</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://zhangbo4881820.gitee.io/myblog/posts/39854/">https://zhangbo4881820.gitee.io/myblog/posts/39854/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://zhangbo4881820.gitee.io/myblog" target="_blank">静待花开</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/myblog/tags/%E6%B6%88%E6%81%AF%E4%B8%AD%E9%97%B4%E4%BB%B6/">消息中间件</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdnjs.cloudflare.com/ajax/libs/social-share.js/1.0.16/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/myblog/posts/23732/" title="Idea配置tomcat"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">Idea配置tomcat</div></div></a></div><div class="next-post pull-right"><a href="/myblog/posts/19354/" title="SpringCloudPractice02"><div class="cover" style="background: var(--default-bg-color)"></div><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">SpringCloudPractice02</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/myblog/posts/43614/" title="RabbitMQ基本操作"><div class="cover" style="background: var(--default-bg-color)"></div><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2019-12-02</div><div class="title">RabbitMQ基本操作</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="this.onerror=null;this.src='/myblog/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">brad 随风起舞</div><div class="author-info__description">有些事情需要一辈子的沉淀</div></div><div class="card-info-data site-data is-center"><a href="/myblog/archives/"><div class="headline">文章</div><div class="length-num">57</div></a><a href="/myblog/tags/"><div class="headline">标签</div><div class="length-num">20</div></a><a href="/myblog/categories/"><div class="headline">分类</div><div class="length-num">25</div></a></div><a id="card-info-btn" href="https://github.com/xxxxxx"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/xxxxx" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a><a class="social-icon" href="mailto:xxxxxx@gmail.com" target="_blank" title="Email"><i class="fas fa-envelope" style="color: #4a7dbe;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">This is my Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#java%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%BF%9E%E6%8E%A5%E5%88%B0%E4%B8%AD%E9%97%B4%E4%BB%B6"><span class="toc-number">1.</span> <span class="toc-text">java客户端连接到中间件</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%8F%82%E6%95%B0%E8%AE%B2%E8%A7%A3"><span class="toc-number">2.</span> <span class="toc-text">参数讲解</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E7%94%9F%E4%BA%A7%E6%B6%88%E6%81%AF"><span class="toc-number">3.</span> <span class="toc-text">生产消息</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%A3%80%E6%9F%A5rabbitmq%E7%8A%B6%E6%80%81"><span class="toc-number">4.</span> <span class="toc-text">检查rabbitmq状态</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E6%B6%88%E6%81%AF"><span class="toc-number">5.</span> <span class="toc-text">消费消息</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%B6%88%E8%B4%B9%E7%BA%BF%E7%A8%8B%E5%92%8C%E9%98%BB%E5%A1%9E%E8%AF%AD%E4%B9%89"><span class="toc-number">5.1.</span> <span class="toc-text">消费线程和阻塞语义</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%BD%BF%E7%94%A8JSON%E5%BA%8F%E5%88%97%E5%8C%96body"><span class="toc-number">6.</span> <span class="toc-text">使用JSON序列化body</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#%E5%AF%B9%E6%B6%88%E6%81%AF%E4%BD%BF%E7%94%A8RPC"><span class="toc-number">7.</span> <span class="toc-text">对消息使用RPC</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/15695/" title="jenkins（1）">jenkins（1）</a><time datetime="2023-09-14T02:17:44.000Z" title="发表于 2023-09-14 10:17:44">2023-09-14</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/22012/" title="wsl的Ubuntu子系统（1）">wsl的Ubuntu子系统（1）</a><time datetime="2023-09-13T08:42:19.000Z" title="发表于 2023-09-13 16:42:19">2023-09-13</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/30302/" title="effective-java-(接口优于抽象类)">effective-java-(接口优于抽象类)</a><time datetime="2023-09-12T08:12:48.000Z" title="发表于 2023-09-12 16:12:48">2023-09-12</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/9473/" title="effective-java(创建和销毁对象--组合的形式优于继承)">effective-java(创建和销毁对象--组合的形式优于继承)</a><time datetime="2023-09-11T08:23:19.000Z" title="发表于 2023-09-11 16:23:19">2023-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/myblog/posts/16107/" title="Hello World">Hello World</a><time datetime="2023-09-07T09:44:01.910Z" title="发表于 2023-09-07 17:44:01">2023-09-07</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2023 By brad 随风起舞</div><div class="framework-info"><span>框架 </span><a href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/myblog/js/utils.js"></script><script src="/myblog/js/main.js"></script><script src="/myblog/js/fancybox.umd.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div class="no-result" id="local-search-results"></div><div id="local-search-stats-wrap"></div></div></div><div id="search-mask"></div><script src="/myblog/js/search/local-search.js"></script></div></div></body></html>